/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.action;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.database.SqlBook;
import model.entities.Book;

/**
 *
 * @author HoangTien
 */
public class BookAction implements Action {

    public void exe(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String url = "/direction.jsp";
        HttpSession session = request.getSession();
        if (session.getAttribute("Categories") == null) {
            request.getRequestDispatcher(url).forward(request, response);
        } else {
            url = "/book.jsp";
            int bookId = Integer.parseInt(request.getParameter("Id"));
            Book book;
            if (session.getAttribute("BookByCategory") == null) {
                SqlBook sqlBook = new SqlBook();
                book = sqlBook.getBook(bookId);
                session.setAttribute("Book", book);
            } else {
                for (Book b : (List<Book>) session.getAttribute("BookByCategory")) {
                    if (b.getBookId() == bookId) { 
                        session.setAttribute("Book", b); 
                        break;
                    }
                }
            }
            request.getRequestDispatcher(url).forward(request, response);
        }
    }
}
